


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    private int maxPathSum = Integer.MIN_VALUE;

    public int maxPathSum(TreeNode root) {
        calculateMaxPathSum(root);
        return maxPathSum;
    }

    private int calculateMaxPathSum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        // 计算左子树的最大路径和
        int leftMax = Math.max(calculateMaxPathSum(root.left), 0);
        // 计算右子树的最大路径和
        int rightMax = Math.max(calculateMaxPathSum(root.right), 0);
        // 当前节点能够构成的最大路径和
        int curMax = root.val + Math.max(leftMax, 0) + Math.max(rightMax, 0);
        // 更新目前最大路径和
        maxPathSum = Math.max(maxPathSum, curMax);

        // 返回子节点下左右子树中较大的路径和
        return root.val + Math.max(leftMax, rightMax);
    }
}